<?php
define('INSTALL_APP_PATH', realpath('./') . '/');
class IndexAction extends BaseAction {
	public function index()
	{
		$lock = APP_PATH . 'Conf/install.lock';
		if (file_exists($lock)) {
			header("Content-type: text/html; charset=utf-8"); 
			echo('请不要重复安装,重新安装请删除 '.APP_PATH . 'Conf/install.lock');
			exit();
		}
		session('env', "ok");
		//环境检测
		$env = $this->check_env();

		//目录文件读写检测
		$dirfile = $this->check_dirfile();

		//函数检测
		$func = $this->check_func();

		$this->assign('env', $env);
		$this->assign('dirfile', $dirfile);
		$this->assign('func', $func);

        $this->display('./Lib/Action/Install/Tpl/index.html');
	}

	public function setup2()
	{
		$lock = APP_PATH . 'Conf/install.lock';
		if (file_exists($lock)) {
			header("Content-type: text/html; charset=utf-8"); 
			echo('请不要重复安装,重新安装请删除 '.APP_PATH . 'Conf/install.lock');
			exit();
		}
		if($this->isPost()){
			$DBHOST = I('DBHOST');
			$DBNAME = I('DBNAME');
			$DBUSER = I('DBUSER');
			$DBPASSWD = I('DBPASSWD');

			$account = I('account');
			$passwd = I('passwd');
			$email = I('email');
			
			$acinfo['account'] = $account;
			$acinfo['passwd'] = $passwd;
			$acinfo['email'] = $email;
			session('acinfo', $acinfo);
			

			//检测数据库配置
			if(empty($DBHOST) || empty($DBNAME) ||  empty($DBUSER) || empty($DBPASSWD) || empty($account) || empty($passwd)){
				$this->error('请填写完整的数据库配置');
			} else {
				$DB['DB_HOST'] = $DBHOST;
				$DB['DB_NAME'] = $DBNAME;
				$DB['DB_USER'] = $DBUSER;
				$DB['DB_PWD'] = $DBPASSWD;
				$DB['DB_TYPE'] = 'mysql';
				$DB['DB_PORT'] = '3306';
				$DB['DB_PREFIX'] = 'yun_';

				$conn = mysql_connect($DBHOST,$DBUSER,$DBPASSWD); 
				if (!$conn) {
					$this->ajaxReturn(0,'数据库连接错误.请填写正确的信息.',0);
					return;
				}
				session('db_config', $DB);
				$this->ajaxReturn(0,'数据库配置正确,请继续下一步',1);
			}
			exit();
		}
        $this->display('./Lib/Action/Install/Tpl/setup2.html');
	}

	public function setup3()
	{
		$lock = APP_PATH . 'Conf/install.lock';
		if (file_exists($lock)) {
			header("Content-type: text/html; charset=utf-8"); 
			echo('请不要重复安装,重新安装请删除 '.APP_PATH . 'Conf/install.lock');
			exit();
		}
		
        $this->display('./Lib/Action/Install/Tpl/setup3.html');
		$this->create_tables();
		$this->write_config();
		$this->register_administrator();
		file_put_contents(APP_PATH . 'Conf/install.lock', '');
	}

	function register_administrator($db, $prefix, $admin, $auth){
		$dbconfig = session('db_config');
		$db = Db::getInstance($dbconfig);
		$acinfo = session('acinfo');
		$password = md5($acinfo['passwd']);
		$email = $acinfo['email'];
		$account = $acinfo['account'];
		$this->show_msg('开始注册创始人帐号...');
		$sql = "INSERT INTO `yun_member` (id,email,account,password,status) VALUES (1,'$email','$account','$password',1)";

		$db->execute($sql);
		$sql = "INSERT INTO  `yun_apps` (`id` ,`mid` ,`title` ,`copyright` ,`isreg`)VALUES (NULL ,  '1',  '云度微信',  '云度微信',  '1')";
		$db->execute($sql);
		$this->show_msg('创始人帐号注册完成！');
	}



	/**
	 * 函数检测
	 * @return array 检测数据
	 */
	function check_func(){
		$items = array(
			array('mysql_connect',     '支持', 'ok'),
			array('file_get_contents', '支持', 'ok'),
			array('fsockopen',         '支持', 'ok'),
			//array('mime_content_type', '支持', 'success'), //该函数非必须
		);

		foreach ($items as &$val) {
			if(!function_exists($val[0])){
				$val[1] = '不支持';
				$val[2] = 'remove';
				$val[3] = '开启';
				session('env', "error");
			}
		}

		return $items;
	}

	/**
	 * 写入配置文件
	 * @param  array $config 配置信息
	 */
	function write_config(){
		$config = session('db_config');
		if(is_array($config)){
			//读取配置内容
			$conf = file_get_contents('./Lib/Action/Install/conf.tpl');
			//替换配置项
			foreach ($config as $name => $value) {
				$conf = str_replace("[{$name}]", $value, $conf);
			}

			//写入应用配置文件
			if(file_put_contents(APP_PATH . 'Conf/config.php', $conf) ){
				$this->show_msg('配置文件写入成功');
			} else {
				$this->show_msg('配置文件写入失败！', 'error');
				session('env', "error");
			}
		}
	}

	/**
	 * 写入入口文件
	 */
	function write_index(){
		//替换入口内容
		$file    = INSTALL_APP_PATH . 'index.php';
		$content = file_get_contents($file);
		$content = preg_replace('/\/\/\[install\].*\/\/\[\/install\]/is', '', $content);
		if(file_put_contents($file, $content)){
			show_msg('入口文件写入成功');
		} else {
			show_msg('入口文件写入失败！', 'error');
			session('error', true);
		}
	}

	/**
	 * 创建数据表
	 * @param  resource $db 数据库连接资源
	 */
	function create_tables($db, $prefix = ''){
		$dbconfig = session('db_config');
		$dbname = $dbconfig['DB_NAME'];
		unset($dbconfig['DB_NAME']);
		$db = Db::getInstance($dbconfig);
		$sql = "CREATE DATABASE IF NOT EXISTS `".$dbname."` DEFAULT CHARACTER SET utf8";
		$db->execute($sql);
		$this->show_msg('创建数据库'.$dbname);
		$dbfile = "./Lib/Action/Install/yunduweixin_db.sql";
		$sql = file_get_contents($dbfile);
		$sql = str_replace("\r", "\n", $sql);
		$sql = explode(";\n", $sql);

		$dbconfig['DB_NAME'] = $dbname;
		$db = Db::getInstance($dbconfig);



		//开始安装
		$this->show_msg('开始安装数据库...');
		foreach ($sql as $value) {

			$value = trim($value);

			if(empty($value)) continue;

			if(substr($value, 0, 12) == 'CREATE TABLE') {
				$name = preg_replace("/^CREATE TABLE IF NOT EXISTS `(\w+)` .*/s", "\\1", $value);
				$msg  = "创建数据表{$name}";
				if(false !== $db->execute($value)){
					$this->show_msg($msg . '...成功');
				} else {
					$this->show_msg($msg . '...失败！', 'error');
					session('error', true);
				}
			} else {
				$db->execute($value);
			}
			
		}
	}

	/**
	 * 目录，文件读写检测
	 * @return array 检测数据
	 */
	function check_dirfile(){
		$items = array(
			array('dir',  '可写', 'success', './Upload'),
			array('dir',  '可写', 'success', './Conf'),
			array('file', '可写', 'success', './Conf/config.php'),
			array('dir',  '可写', 'success', './Runtime'),
			array('file', '可写', 'success', './index.php'),
		);

		foreach ($items as &$val) {
			if('dir' == $val[0]){
				if(!is_writable(INSTALL_APP_PATH . $val[3])) {
					if(is_dir($items[1])) {
						$val[1] = '可读';
						$val[2] = 'remove';
						session('env', "ok");
					} else {
						$val[1] = '不存在';
						$val[2] = 'remove';
						session('env', "error");
					}
				}
			} else {
				if(file_exists(INSTALL_APP_PATH . $val[3])) {
					if(!is_writable(INSTALL_APP_PATH . $val[3])) {
						$val[1] = '不可写';
						$val[2] = 'remove';
						session('env', "error");
					}
				} else {
					if(!is_writable(dirname(INSTALL_APP_PATH . $val[3]))) {
						$val[1] = '不存在';
						$val[2] = 'remove';
						session('env', "error");
					}
				}
			}
		}

		return $items;
	}

	/**
	 * 及时显示提示信息
	 * @param  string $msg 提示信息
	 */
	function show_msg($msg, $class = ''){
		echo "<script type=\"text/javascript\">showmsg(\"{$msg}\", \"{$class}\")</script>";
		flush();
		ob_flush();
	}

	/**
	 * 系统环境检测
	 * @return array 系统环境数据
	*/
	function check_env(){
		$items = array(
			'os'      => array('操作系统', '不限制', '类Unix', PHP_OS, 'ok'),
			'php'     => array('PHP版本', '5.2', '5.2+', PHP_VERSION, 'ok'),
			// 'mysql'   => array('MYSQL版本', '5.0', '5.0+', '未知', 'success'), //PHP5.5不支持mysql版本检测
			'upload'  => array('附件上传', '不限制', '2M+', '未知', 'ok'),
			'gd'      => array('GD库', '2.0', '2.0+', '未知', 'ok'),
			'disk'    => array('磁盘空间', '10M', '不限制', '未知', 'ok'),
		);

		//PHP环境检测
		if($items['php'][3] < $items['php'][1]){
			$items['php'][4] = 'remove';
			session('env', "error");
		}

		//数据库检测
		// if(function_exists('mysql_get_server_info')){
		// 	$items['mysql'][3] = mysql_get_server_info();
		// 	if($items['mysql'][3] < $items['mysql'][1]){
		// 		$items['mysql'][4] = 'error';
		// 		session('error', true);
		// 	}
		// }

		//附件上传检测
		if(@ini_get('file_uploads'))
			$items['upload'][3] = ini_get('upload_max_filesize');

		//GD库检测
		$tmp = function_exists('gd_info') ? gd_info() : array();
		if(empty($tmp['GD Version'])){
			$items['gd'][3] = 'remove';
			$items['gd'][4] = 'error';
			session('env', "error");
		} else {
			$items['gd'][3] = $tmp['GD Version'];
		}
		unset($tmp);

		//磁盘空间检测
		if(function_exists('disk_free_space')) {
			$items['disk'][3] = floor(disk_free_space(INSTALL_APP_PATH) / (1024*1024)).'M';
		}

		return $items;
	}
}